package middleware

import (
	"context"
	"net/http"

	kitJwt "github.com/go-kit/kit/auth/jwt"
	"github.com/go-kit/kit/endpoint"
	"github.com/golang-jwt/jwt/v4"
)

func JwtMiddleware() endpoint.Middleware {
	return func(e endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {

			// 从请求头中，获取到token
			req := request.(*http.Request)
			token := req.Header.Get("token")
			// 将token放到上下文中
			ctx = context.WithValue(ctx, kitJwt.JWTContextKey, token)

			key := func(*jwt.Token) (interface{}, error) {
				return []byte("test_signing_key"), nil
			}

			parser := kitJwt.NewParser(key, jwt.SigningMethodHS256, kitJwt.MapClaimsFactory)

			nextStep := parser(e)

			return nextStep(ctx, request)

		}
	}
}
